import tkinter as tk
from tkinter import filedialog, dialog, StringVar, IntVar
from tkinter.filedialog import askdirectory
from tkinter import ttk
from audio2mouth import *
import os
import sys

# 全局变量
wav_path=''

def load_wav():
    global wav_path
    filename = filedialog.askopenfilename(initialdir ='.\\',title=r"Select your audio file(format is .wav)", filetypes=[('Audio','.wav')])
    wav_path = filename
    state_var.set('Audio loaded')

# 自动创建输出文件夹
def is_output_path_exist():
    if not os.path.exists('.\output_file'):
        os.mkdir('.\output_file')
is_output_path_exist()

# 根据选择设置默认系数
def set_default_factor(event):
    if 列表.get() == "fun model":
        趣味模式.place(relx=0.32, rely=0.7)
        return 
    else:
        趣味模式.place_forget()
    default_dist = {"texture model": 0.16,"curve model": 0.45}
    factor_var.set(default_dist[列表.get()])

def factor_Spinbox_up(event):
    print('up')
# GUI
def GUI_main():
    global state_var,列表,factor_var,factor_Spinbox,趣味模式
    window = tk.Tk()
    window.title('Audio-keyframes converter(English version)')
    window.geometry('800x600+460+260')

    author = tk.Label(window,text='Authors:\nExcitablecell\nStanwade\nttrtty5',font=14,width=1,height=1,justify="left").place(relx=-0.275, rely=-0.35, relheight=2.25, relwidth=0.889)
    # author = tk.Label(window,text='作者:\n亢体动画\n瓦斯弹\nttrtty5',font=14,width=1,height=1,justify="left").place(relx=-0.32, rely=-0.35, relheight=2.25, relwidth=0.889)
    l = tk.Label(window,text=r"Select your audio file(format is .wav)",font=14,width=30,height=2).place(relx=0.03, rely=0.05, relheight=0.1, relwidth=0.889)
    

    # 运行状态标签
    state_var = StringVar()
    state_label = tk.Label(window,textvariable=state_var,font=14,width=30,height=2).place(relx=0.03, rely=0.9, relheight=0.1, relwidth=0.889)
    
    b = tk.Button(window,text ="Select audio", font=14,command = load_wav).place(relx=0.35, rely=0.19, relheight=0.09, relwidth=0.3)
    
    # 调整系数
    factor_var = IntVar()
    factor_var.set(0.16)
    factor_label = tk.Label(window,text='mouth scale: ',font=14,width=30,height=2).place(relx=0.27, rely=0.58, relheight=0.1, relwidth=0.3)
    # ,textvariable=factor_var
    factor_Spinbox = tk.Spinbox(window,from_=-10000,to_=10000,format='%10.2f',increment=0.1,textvariable=factor_var)
    factor_Spinbox.place(relx=0.53, rely=0.58, relheight=0.09, relwidth=0.15)

    # 嘴型下拉框
    miobj_template = ("texture model","curve model","fun model")
    列表 = ttk.Combobox(window,font=12)
    列表["values"] = miobj_template
    列表.configure(state = "readonly")
    列表.current(0)
    列表.place(relx=0.32, rely=0.5)
    列表.bind("<<ComboboxSelected>>", set_default_factor)
    
    趣味模式 = ttk.Combobox(window,font=12)
    趣味模式["values"] = ('X_scale', 'y_sca', 'z_sca', 'x_roa', 'y_roa', 'z_roa')
    趣味模式.configure(state = "readonly")
    趣味模式.current(0)
    趣味模式.place(relx=0.32, rely=0.7)
    趣味模式.place_forget()
    趣味模式.bind("<<ComboboxSelected>>", set_default_factor)

    output_button = tk.Button(window,text ="output", font=14, command = main).place(relx=0.35, rely=0.8, relheight=0.09, relwidth=0.3)

    window.mainloop()

# audio2mouth函数
def main():
    input_Data = sys.argv[1]
    global wav_path,state_var,factor_Spinbox
    if wav_path=='':
        state_var.set('Audio is not loaded!')
        return 
    vol = getVolume(wav_path)
    vol = normalization(vol, 40, float(factor_Spinbox.get()))
    time = getTime(wav_path, vol)
    total = len(time)  # 总帧数填到total里
    scale = vol  # 每个尺寸填到scale列表里（覆盖这里面的0-5）

    kind = 列表.get()
    flag = 0
    if kind == 'texture model':
        with open(r"miobj_template/texturemouth/template_mouth.miobject", "r")as f:
            MiFileData = f.read()
        MiDict = json.loads(MiFileData)
        num = 0
        for num in range(500):
            if (MiDict['timelines'][num]['name'] == 'mouth'):
                break

        for j in range(total):
            if scale[j] > 0.01:
                flag = 1
                MiDict['timelines'][num]['keyframes'][j + 1] = {
                    "SCA_X": 0.09,
                    "SCA_Z": scale[j],
                }
            elif scale[j] <= 0.01 and flag == 1:
                flag = 0
                MiDict['timelines'][num]['keyframes'][j + 1] = {
                    "SCA_X": 0.09,
                    "SCA_Z": 0,
                    "TEXTURE_OBJ": "D3RD97B56CP34V34",
                    "VISIBLE": False

                }
        copyfile("miobj_template/texturemouth/he.png","output_file/he.png")
        copyfile("miobj_template/texturemouth/h x.png","output_file/h x.png")
    elif kind == 'curve model':
        with open(r"miobj_template/curvemouth/curvemouth.miobject", "r")as f:
            MiFileData = f.read()
        MiDict = json.loads(MiFileData)
        num = 0
        for num in range(500):
            if (MiDict['timelines'][num]['name'] == 'mouth_control'):
                break

        for j in range(total):
            scale[j] *= 4
            MiDict['timelines'][num]['keyframes'][j + 1] = {
                "POS_X": 0,
                "POS_Y": 4.00421,
                "POS_Z": 0.72884,
                "SCA_X": 0.375,
                "SCA_Y": 0.5,
                "SCA_Z": scale[j],
                "RGB_MUL": "#FFD2AA",
                "MIX_COLOR": "#FFC029"
            }
        copyfile("miobj_template/curvemouth/curvemouth.mimodel","output_file/curvemouth.mimodel")
        copyfile("miobj_template/curvemouth/Default texture.png","output_file/Default texture.png")
    elif kind == 'fun model': # 自♂由模式，将响度映射到其它变量上去，设置了6个默认值，同时也支持手动输入，例如输入BEND_ANGLE_X
        print('操作比较复杂，建议查看说明书')
        with open(r"miobj_template/funmodel/fun_template.miobject", "r")as f:
            MiFileData = f.read()
        MiDict = json.loads(MiFileData)
        num = 0
        for num in range(500):
            if (MiDict['timelines'][num]['name'] == 'funmodel'):
                break
        趣味模式_dist = {'X尺寸': '1', 'y尺寸': '2', 'z尺寸': '3', 'x旋转': '4', 'y旋转': '5', 'z旋转': '6'}
        varName = 趣味模式.get()
        print(varName)
        if varName == '1':
            varName = 'SCA_X'
        elif varName == '2':
            varName = 'SCA_Y'
        elif varName == '3':
            varName = 'SCA_Z'
        elif varName == '4':
            varName = 'ROT_X'
        elif varName == '5':
            varName = 'ROT_Y'
        elif varName == '6':
            varName = 'ROT_Z'
        else:
            varName = input('输入变量名：')
        for j in range(totalFrame):
            MiDict['timelines'][num]['keyframes'][j + 1] = {
                varName: scale[j]
            }

    else:
        print('转换失败，请填入正确序号！')
        print("we dont have this kind of mouth model!!!")
        print("convert fail!!!")
    MiJson = json.dumps(MiDict, indent='    ', ensure_ascii=False)  # 字典转json文本
    fn = os.path.split(wav_path)[1]
    output_path=r"output_file/" + "output.miobject"
    with open(output_path, "w+") as f:  # 新建文件
        f.write(MiJson)  # 文本写入文件
    print("convert complete!!! press any key to exit")
    state_var.set('已输出到'+ output_path)



if __name__ == "__main__":
    GUI_main()






